/**  定义user相关的接口 */
const express = require('express');
const router = express.Router();
const Joi = require('joi');
const Response = require('../utils/Response.js');

// 引入mysql连接池
const pool = require('../utils/db.js');

const jwt = require('jsonwebtoken');
const SECRET_KEY = 'JWT_SECRET_KEY';

/**
 * 添加用户接口
 * @param:
 *   {email,phone,pwd}
 * @return:
 *   {code:200, msg:'ok'}
 */
router.post('/user/register', async (req, resp) => {
  let { email, phone, pwd } = req.body; // post请求参数在req.body中

  // 表单验证
  let schema = Joi.object({
    email: Joi.string().required(), // 必填
    phone: Joi.string().required(), // 必填
    pwd: Joi.string().required(), // 必填
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }
  // 表单验证通过，执行添加操作
  let sql = 'insert into user_info(email,phone,pwd) values (?,?,?)';
  pool.query(sql, [email, phone, pwd], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok());
  });
});

// 检查手机号是否重复
router.get('/checkPhone', (req, resp) => {
  let { phone } = req.query;
  // 表单验证
  let schema = Joi.object({
    phone: Joi.string().required(), // 必填
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }
  // 执行查询
  let sql = `select count(*) as count from user_info where phone=?`;
  pool.query(sql, [phone], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result && result[0].count == 0) {
      // console.log(phone);
      // console.log(result[0].count);
      // 没查到
      resp.send(Response.error(200, '手机号不存在'));
    } else {
      console.log(phone);
      resp.send(Response.error(202, '手机号已存在'));
    }
  });
});

// 检查邮箱是否重复
router.get('/checkEmail', (req, resp) => {
  let { email } = req.query;
  // 表单验证
  let schema = Joi.object({
    email: Joi.string().required(), // 必填
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }
  // 执行查询
  let sql = `select count(*) as count from user_info where email=?`;
  pool.query(sql, [email], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result && result[0].count == 0) {
      // 没查到
      resp.send(Response.error(200, '邮箱不存在'));
    } else {
      resp.send(Response.error(202, '邮箱已存在'));
    }
  });
});

/**
 * 用户登录接口
 * @param:{phone,pwd}
 *
 */
router.post('/user/login', (req, resp) => {
  let { phone, pwd } = req.body;
  // 表单验证
  let schema = Joi.object({
    phone: Joi.string().required().pattern(new RegExp('^1[3-9]\\d{9}$')), // 必填
    pwd: Joi.string().required().pattern(new RegExp('^\\w{6,15}$')), // 必填
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }
  // 查询数据库，账号密码是否填写正确
  // phone, pwd
  // console.log(phone);
  let sql = 'select * from user_info where phone=?&&pwd=?';
  pool.query(sql, [phone, pwd], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.length == 0) {
      resp.send(Response.error(1001, '账号密码输入错误'));
    } else {
      // 获取登录用户对象
      let user = result[0];
      // 为该用户颁发一个token字符串，未来该客户端若做发送其他请求，则需要在请求Header中携带token，完成状态管理。
      let payload = { id: user.uid, uname: user.uname };
      let token = jwt.sign(payload, SECRET_KEY, { expiresIn: '1d' });
      // 返回user对象与token字符串
      user.pwd = undefined;
      resp.send(Response.ok({ user, token }));
    }
  });
});

/**
 * 修改用户信息接口
 */
router.post('/user/update', (req, resp) => {
  let { id, pwd, phone, uname, sex, email, user_number } = req.body; // post请求参数在req.body中

  // 表单验证
  let schema = Joi.object({
    id: Joi.number().required(),
    pwd: Joi.string().required(),
    phone: Joi.string().required(),
    uname: Joi.string().required(),
    sex: Joi.number(),
    email: Joi.string().required(),
    user_number: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }

  // 表单验证通过，执行添加操作
  let sql = `update user_info set pwd=?, phone=?, uname=?, sex=?, email=?, user_number=? where uid=?`;
  pool.query(
    sql,
    [pwd, phone, uname, sex, email, user_number, id],
    (error, result) => {
      if (error) {
        resp.send(Response.error(500, error));
        throw error;
      }
      resp.send(Response.ok());
    }
  );
});

/**
 * 通过ID查询用户接口
 * @param:
 *   id:   uid
 * @return:
 *   {code:200, msg:'ok', data:{}}
 */
router.get('/user/query', (req, resp) => {
  let { id } = req.query;
  // 表单验证
  let schema = Joi.object({
    id: Joi.string().required(), // 必填
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }

  // 执行查询业务
  let sql = 'select * from user_info where uid=?';
  pool.query(sql, [id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result && result.length == 0) {
      // 没查到
      resp.send(Response.ok(null));
    } else {
      resp.send(Response.ok(result[0]));
    }
  });
});

/**
 * 注销用户接口
 * @param:{id}
 * @return:{code:200,msg:'ok'}
 */
router.post('/user/del', (req, resp) => {
  let { id } = req.body;

  // 表单验证
  let schema = Joi.object({
    id: Joi.string().required(), // 必填
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }

  // 执行删除业务
  let sql = 'delete from user_info where uid = ?';
  pool.query(sql, [id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok());
  });
});

//
// 将router对象导出
module.exports = router;
